package processors

import (
	"fmt"
	"go-demo/designpattern/templatemethod/ordercenter"
)

// 团购订单处理器
type GroupBuyOrderProcessor struct {
	DefaultOrderProcessor
}

func (p *GroupBuyOrderProcessor) BeforeProcess(order *ordercenter.Order) {
	fmt.Println("=== 开始处理团购订单 ===")
}

func (p *GroupBuyOrderProcessor) AfterProcess(order *ordercenter.Order) {
	fmt.Println("=== 团购订单处理完成 ===")
	fmt.Println("更新团购活动参与人数...")
}

// 重写验证订单方法
func (p *GroupBuyOrderProcessor) ValidateOrder(order *ordercenter.Order) error {
	fmt.Println("执行团购订单验证...")

	// 先调用默认验证
	if err := p.DefaultOrderProcessor.ValidateOrder(order); err != nil {
		return err
	}

	// 添加团购特有验证
	if len(order.Items) < 5 {
		return fmt.Errorf("团购订单 %s 至少需要5件商品", order.ID)
	}

	fmt.Println("验证团购活动有效性...")
	return nil
}

// 重写应用折扣方法
func (p *GroupBuyOrderProcessor) ApplyDiscounts(order *ordercenter.Order) {
	fmt.Println("应用团购折扣...")
	discountRate := 0.1
	if len(order.Items) >= 5 {
		order.Discount = order.TotalAmount * discountRate
		order.FinalAmount = order.TotalAmount - order.Discount
		fmt.Printf("应用 %.0f%% 团购折扣, 优惠金额: ￥%.2f\n", discountRate*100, order.Discount)
	}
}

// 重写扣减库存方法
func (p *GroupBuyOrderProcessor) DeductInventory(order *ordercenter.Order) error {
	fmt.Println("团购订单特殊库存扣减...")
	for _, item := range order.Items {
		fmt.Printf("  - 商品 %s: 扣减团购预留库存 %d 件\n", item.ProductID, item.Quantity)
	}
	return nil
}

// 实现处理接口
func (p *GroupBuyOrderProcessor) Process(order *ordercenter.Order) error {
	p.BeforeProcess(order)
	defer p.AfterProcess(order)
	return nil
}
